package com.yocard.yxyd.adapter;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.SparseArrayCompat;
import android.view.ViewGroup;
import android.webkit.ValueCallback;

import com.yocard.yxyd.base.AppContext;
import com.yocard.yxyd.ui.fragment.OrderListFragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2019/4/2.
 */
public class OrderFragmentAdapter extends FragmentPagerAdapter {

    private FragmentManager fm;
    private ValueCallback<Integer> callback;
    private List<String> titles;
    private SparseArrayCompat<WeakReference<Fragment>> holder;
    protected final List<Class> fragments;
    protected int containerId;

    public OrderFragmentAdapter(FragmentManager fm, ValueCallback<Integer> callback) {
        super(fm);
        this.fm = fm;
        this.callback = callback;
        titles = new ArrayList<>();
        titles.add("全部");
        titles.add("信用贷");
        titles.add("抵押贷");
        titles.add("车主贷");
        titles.add("装修贷");
        titles.add("银行贷");

        fragments = new ArrayList<>();
        fragments.add(OrderListFragment.class);
        fragments.add(OrderListFragment.class);
        fragments.add(OrderListFragment.class);
        fragments.add(OrderListFragment.class);
        fragments.add(OrderListFragment.class);
        fragments.add(OrderListFragment.class);

        this.holder = new SparseArrayCompat<>(titles.size());
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        containerId = container.getId();
        Object item = super.instantiateItem(container, position);
        if (item instanceof Fragment) {
            holder.put(position, new WeakReference<Fragment>((Fragment) item));
        }
        return item;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        holder.remove(position);
        super.destroyItem(container, position, object);
    }

    @Override
    public Fragment getItem(int i) {
        OrderListFragment fragment = (OrderListFragment) Fragment.instantiate(AppContext.getContext(), fragments.get(i).getName());
        fragment.setRefreshCallbacl(callback);
        fragment.setViewPagePos(i);
        return fragment;
    }

    @Override
    public int getCount() {
        return titles.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }

    public Fragment getFragmentAt(int position) {
        String tag = "android:switcher:" + containerId + ":" + getItemId(position);
        return fm.findFragmentByTag(tag);
    }
}
